<template>
    <div style="height: 100%;width: 100%">
            <!--操作弹窗没有确认按钮-->
        <div style="height: 100%;width: 100%" v-if="procedure =='one'">
            <div v-if="mdl.status == 'Draft'" slot="toolbar">
                <a-button type="primary" @click="saveNews">{{$ti18('rxList.deploy','发布')}}</a-button>
            </div>
            <rx-layout>
                <div slot="center">
                    <a-spin :tip="i18n('processing','正在处理...')" :spinning="isSpinning">
                        <div>
                            <a-form :form="form">
                                <a-divider>{{i18n('stepOne','第1步 选择流程与表单分类')}}</a-divider>
                                <a-row>
                                    <a-col :span="11">
                                        <a-form-item :label="i18n('selectBpm','选择流程分类')">
                                            <a-tree-select
                                                @change="onBpmTreeChange"
                                                :treeData="bpmTreeData"
                                                v-model="treeId"
                                                style="width: 100%"
                                                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                                                :placeholder="i18n('pleaseSelect','请选择...')"
                                            >
                                            </a-tree-select>
                                        </a-form-item>
                                    </a-col>
                                    <a-col :span="11" style="margin-left: 8%">
                                        <a-form-item :label="i18n('selectForm','选择表单分类')">
                                            <a-tree-select
                                                @change="onFormTreeChange"
                                                :treeData="formTreeData"
                                                v-model="formPcTree"
                                                style="width: 100%"
                                                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                                                :placeholder="i18n('pleaseSelect','请选择...')"
                                            >
                                            </a-tree-select>
                                        </a-form-item>
                                    </a-col>
                                </a-row>
                                <a-divider v-if="showStepTwo">{{i18n('stepTwo','第2步 选择流程解决方案')}}</a-divider>
                                <a-upload-dragger
                                    v-if="showStepTwo"
                                    class="self-dragger"
                                    :file-list="fileList"
                                    :remove="handleRemove"
                                    :before-upload="beforeUpload"
                                    :customRequest="()=>{}"
                                >
                                    <p v-if="!fileName">
                                        <i class="iconfont iconshangchuan1 upicon"></i>
                                    </p>
                                    <p v-if="!fileName" class="ant-upload-hint">
                                        <span class="up-title">{{i18n('selectFile','选择流程解决方案的压缩文件，或拖拽文件到此区域')}}</span>
                                    </p>
                                    <div v-if="fileName" class="file-list-box">
                                        <p><i class="iconfont iconfile-zip-fill fileicon"></i></p>
                                        <p class="xlsx">{{ fileName }}</p>
                                        <p class="package">{{i18n('reselect','重新选择压缩包')}}</p>
                                        <!-- <i @click.stop="handleRemove" class="iconfont icontrash updel"></i> -->
                                    </div>
                                    <div class="upd-btn" v-if="fileName">
                                        <a-button style="width: 100%" type="primary" :loading="uploading" @click.stop="handleUpload"
                                        >{{i18n('list.importProcess','导入流程')}}</a-button
                                        >
                                    </div>
                                </a-upload-dragger>
                                <a-row v-if="showImportBtn">
                                    <a-col :span="24">
                                        <a-button type="primary" @click="handleUpload()"> {{$ti18('rxList.importBtn','导入')}} </a-button>
                                    </a-col>
                                </a-row>
                            </a-form>
                        </div>
                    </a-spin>
                </div>
            </rx-layout>
        </div>
        <!--手动执行sql脚本-->
        <div v-if="procedure =='two'" style="width: 100%;height: 100%">
              <rx-dialog @handOk="okFun" @cancel="cancel">
                  <a-form :form="form">
                      <a-divider v-if="showSqls && procedure =='two'">{{i18n('stepThree','第3步 手动执行SQL语句')}}</a-divider>
                      <a-row v-if="showSqls && procedure =='two'">
                          <a-col :span="24">
                              <div style="height: 200px; box-sizing: border-box; width: 100%; padding-right: 1px">
                                  <rx-monaco-editor ref="monacoes" :language="monacoeLanguage" v-model="updataSqls">
                                  </rx-monaco-editor>
                              </div>
                          </a-col>
                      </a-row>
                  </a-form>
              </rx-dialog>
        </div>
        <!-- 导入的结果-->
        <div v-if="procedure =='three'">
            <div v-if="state">
                <div class="suc-icon-box"><i class="iconfont iconsuccess_fill upsuccess"></i></div>
                <div class="suc-text-box">{{i18n('importSuccess','成功导入流程')}}
                </div>
            </div>
            <div v-else>
                <div class="suc-icon-box"><i class="iconfont iconicon-test28 failing"></i></div>
                <div class="suc-text-box">{{i18n('importFail','导入流程失败')}}
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import BpmDefApi from '@/api/bpm/core/bpmDef'
import { BaseForm, RxDialog, RxLayout, Util, RxMonacoEditor } from '@lowcode/jpaas-common-lib'
import ACol from 'ant-design-vue/es/grid/Col'
import RxCategoryTreeeditor from '@/components/redxun/rx-category-treeeditor'
import SysTreeApi from '@/api/system/core/sysTree'


export default {
  name: 'bpmdef-import',
  mixins: [BaseForm],
  components: {
    ACol,
    RxDialog,
    RxMonacoEditor,
    RxCategoryTreeeditor,
  },
  props: {
    layerid: String,
    lydata: Object,
    destroy: Function,
  },
  data() {
    return {
      monacoeLanguage: 'html',
      isSpinning: false,
      showImportBtn: false,
      showSqls: false,
      updataSqls: '',
      fileList: [],
      file: {},
      formPcTree: '',
      fileZipTypes: ['application/x-zip-compressed', 'application/zip'],
      bpmTreeData: [],
      formTreeData: [],
      fileName: '',
      uploading: false,
      selectVal: undefined,
      bpmSelectVal: undefined,
      formSelectVal: undefined,
      treeId: '',
      procedure:'one',
      state:false,//导入成功还是失败
    }
  },
  computed: {
    //是否时独立打开审批页面还是使用的统一URL打开
    showStepTwo() {
      return this.formPcTree && this.treeId
    },
  },

  mounted() {
    this.loadTreeData()
  },
  methods: {
    i18n(name,text,key){
          return this.$ti18(name,text,"bpmDef",key);
    },
    beforeUpload(file) {
      console.log(file)
      this.fileList = [file]
      this.file = file
      this.fileName = file.name
      return false
    },
    handleRemove(file) {
      console.log(66)
      this.fileList = []
      this.fileName = ''
    },
    handleChange(info) {
      const status = info.file.status
      if (status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (status === 'done') {
        this.fileList = []
        if (info.file.response.success) {
          this.$message.success(`${info.file.response.data}`)
        } else {
          this.$message.error(`${info.file.response.data}`)
        }
      } else if (status === 'error') {
        this.fileList = []
        this.$message.error(`${info.file.name}` + this.i18n('uploadFail','文件上传失败.'))
      }
    },
    loadTreeData() {
      SysTreeApi.getByCatKey('BPM', this.curApp.appId).then((res) => {
        var ary = Util.listToTree(res, 'treeId', 'parentId')
        Util.genTreeData(ary, 'name', 'treeId', 'treeId')
        this.bpmTreeData = ary
        console.log(this.bpmTreeData)
      })

      SysTreeApi.getByCatKey('FORM', this.curApp.appId).then((res) => {
        var ary = Util.listToTree(res, 'treeId', 'parentId')
        Util.genTreeData(ary, 'name', 'treeId', 'treeId')
        this.formTreeData = ary
        console.log(this.formTreeData)
      })
    },
    onBpmTreeChange() {
      console.log(this.treeId)
      //this.$emit("onChange");
    },
    onFormTreeChange() {
      console.log(this.formPcTree)
      //this.$emit("onChange");
      //this.formPcTree = curRow.treeId;
    },
    handSelect(curRow) {
      this.formPcTree = curRow.treeId
    },
    removeFile(info) {
      this.fileList.splice(0, 1)
      this.file = {}
    },
    beforeFileUpload(file) {
      if (!file || !file.type || this.fileZipTypes.indexOf(file.type) == -1) {
        this.$confirm({
          title: this.i18n('warning','警告'),
          zIndex: 20000,
          content: this.i18n('correctFile','请选择需要正确的压缩文件（zip格式）！'),
          okText: this.$ti18('rxForm.okBtn','确定'),
          cancelText: this.$ti18('rxForm.cancelBtn','取消'),
        })
        return
      }
      this.showImportBtn = true
      this.file = file
      this.fileList.push({
        uid: file.uid,
        name: file.name,
        status: 'done',
        url: null,
      })
      return true
    },
    async uploadFile(formData, type) {
      let self = this
      this.isSpinning = true
      this.uploading = true
      await BpmDefApi.doImport(formData).then((res) => {
        this.isSpinning = false
        if (!res.success) {
          this.uploading = false;
          this.procedure = "three";
          this.state = false
          return
        }
        this.uploading = false;
          this.state = true;
        //self.$message.info(this.i18n('importOk','导入成功！'))
        Util.closeWindow(this, 'ok')
        self.getUpdataSqls(res.data)
      })
    },
    getUpdataSqls(data) {
      var sqls = []
      for (var i = 0; data && i < data.length; i++) {
        var sqlObj = data[i]
        sqls.push(sqlObj.sql)
      }
      if (sqls.length > 0) {
        this.showSqls = true;
        this.procedure ="two";
        this.updataSqls = sqls.join('\n')
      }else {
          this.procedure = "three";
      }
    },
    handleUpload() {
      const formData = new FormData()
      let timestamp = new Date().getTime()
      formData.append('zipFile', this.file)
      formData.append('treeId', Util.encryptWord(this.treeId,true))
      formData.append('formPcTreeId', Util.encryptWord(this.formPcTree,true))
      this.uploadFile(formData)
    },
    okFun() {
        var _this =this;
        this.$confirm({
            title: this.i18n('warning','警告'),
            zIndex: 20000,
            content: this.i18n('executeSQL','将执行物理表变更操作,你是否执行成功所有SQL?否则将丢失数据!!!'),
            okText: this.$ti18('rxForm.okBtn','确定'),
            cancelText: this.$ti18('rxForm.cancelBtn','取消'),
            onOk() {
                _this.procedure ='three'
            },
            onCancel(){
                _this.procedure ='three'
            }
        })
    },
    cancel() {
      Util.closeWindow(this, 'cancel')
    },
  },
}
</script>
<style scoped>
.title-div {
  padding: 10px 0;
}

* >>> .ql-snow .ql-picker-label::before {
  vertical-align: top;
}

* >>> .ql-snow .ql-color-picker .ql-picker-label svg,
* >>> .ql-snow .ql-icon-picker .ql-picker-label svg {
  vertical-align: top;
}

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.package{
    color: #4285f4;
    font-size: 14px;
    margin-top: 21px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.import-content {
  margin-top: 16px;
  height: 180px;
}
.upicon {
  font-size: 41px;
  color: #4285f4;
}
.zip-list {
  position: relative;
}
.self-dragger >>> .ant-upload-drag {
  height: 314px;
}
.self-dragger >>> .ant-upload-list {
  display: none;
}
.ant-upload-hint .up-title {
  display: inline-block;
    font-size: 18px;
    color: #333333;
    margin-top: 20px;
}
.updel {
  font-size: 16px;
}
.file-list-box {
  /* width: 330px;
  margin: 0 auto;
  margin-top: 20px;
  margin-top: 10px;
  margin-bottom: 4px; */
  /* display: flex;
  justify-content: space-between; */
}
.fileicon {
  font-size: 45px;
  color: #4285f4;
  margin-right: 8px;
  vertical-align: middle;
}
.xlsx {
  font-family: MicrosoftYaHei;
  font-size: 18px;
  font-weight: normal;
  font-stretch: normal;
  line-height: 26px;
  letter-spacing: 1px;
    margin-top: 20px;
    color: #333333;
}
.upd-btn {
  width: 330px;
  margin: 0 auto;
  margin-top: 8px;
}
.upsuccess {
  font-size: 41px;
  color: #52c319;
}
.failing{
    font-size: 41px;
    color: #f80636;
}
.suc-icon-box {
  text-align: center;
}
.suc-text-box {
  text-align: center;
  font-size: 18px;
  color: #666;
  margin-top: 6px;
}
.suc-content-box {
  text-align: center;
  margin-top: 4px;
}
.suc-blue {
  color: #4285f4;
}
.suc-green {
  color: #52c319;
}
.suc-red {
  color: red;
}
</style>